<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>添加/编辑动态反馈事项</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <el-form label-width="100px" ref="editForm">
          <el-form-item label="所属年段：">
            <el-select v-model="section_id" placeholder="选择年段" size="small">
              <el-option :label="item.section_name" :value="item.id.toString()" v-for="(item, index) in sectionList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上级类目：">
            <el-select v-model="parent_id" :disabled="disabledStatus" placeholder="选择上级类目" size="small"
                       @change="changeParentsFn()">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in selectList"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="反馈事项：">
            <el-input v-model="name" placeholder="动态反馈事项" size="small"></el-input>
          </el-form-item>
          <el-form-item label="排序值：">
            <el-input-number v-model="display_order" :min="0" size="small" placeholder="数字越小排序越靠前"></el-input-number>
          </el-form-item>
          <el-form-item label="事项类型：">
            <el-radio-group v-model="type">
              <el-radio :label="0">打勾项</el-radio>
              <el-radio :label="1">文字描述项</el-radio>
              <el-radio :label="2">图片视频上传项</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="事项来源：">
            <el-radio-group v-model="source">
              <el-radio :label="1">老师填写</el-radio>
              <el-radio :label="2">家长填写</el-radio>
              <el-radio :label="3">老师和家长都可填写</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="事项描述：">
            <el-input
                type="textarea"
                placeholder="事项描述"
                v-model="desc"
                maxlength="500"
                size="small"
                rows="4"
                show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="选项内容：" v-if="type === 0">
            <div v-for="(option, index) in options" :key="index" class="option-item">
              <el-input
                v-model="options[index].value"
                placeholder="请输入选项内容"
                size="small"
              ></el-input>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeOption(index)"
                v-if="index > 0"
              ></el-button>
            </div>
            <el-button type="primary" size="small" @click="addOption">添加选项</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click.native="closePOpup" size="small">取消</el-button>
        <el-button size="small" type="primary" @click="checkEditFn">确定保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {DailyFeedbackCateAdd, DailyFeedbackCateEdit} from "@/api/admin/dailyFeedback"
import {sectionIndex} from "@/api/admin/class"

export default {
  props: ['visible', 'optionData', 'selectList', 'activeName', 'optionType'],
  components: {},
  data() {
      return {
        dialogVisible: false,
        name: '',
        options: [{value: ''}], // 选项列表
        parent_id: 0,
        disabledStatus: false,
        type: 0,
        display_order: 0,
        desc: '',
        fileList: [],
        section_id: '',
        sectionList: [],
        source: 3 // 默认老师和家长都可填写
      }
    },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        if (this.optionType === 'add' && this.optionData) {
          this.parent_id = this.optionData.id
          this.disabledStatus = true
          this.section_id = this.optionData.section_id || ''
        }
        if (this.optionType === 'edit' && this.optionData.parent_id) {
          this.parent_id = this.optionData.parent_id
          this.disabledStatus = true
        }
        if (this.optionType === 'edit' && !this.optionData.parent_id) {
          this.parent_id = 0
          this.disabledStatus = true
        }
        if (this.optionType === 'edit') {
          this.type = this.optionData ? this.optionData.type : 0
          this.name = this.optionData ? this.optionData.name : ''
          this.display_order = this.optionData && this.optionData.display_order !== undefined ? this.optionData.display_order : 0
          this.desc = this.optionData ? this.optionData.desc || this.optionData.description || '' : ''
          this.section_id = this.optionData ? this.optionData.section_id : ''
          // 修正source字段的设置逻辑，确保能正确处理0或null值
          this.source = this.optionData && this.optionData.source !== undefined && this.optionData.source !== null ? this.optionData.source : 3
          // 初始化选项列表 - 从description字段解析（分号分隔）
          if (this.type === 0 && this.optionData && this.optionData.description) {
            // 按分号分隔多个选项
            const optionValues = this.optionData.description.split(';').map(opt => opt.trim()).filter(opt => opt)
            if (optionValues.length > 0) {
              // 将每个选项值转换为选项对象
              this.options = optionValues.map(value => ({value}))
            } else {
              // 如果没有有效选项，创建一个空选项
              this.options = [{value: ''}]
            }
          } else {
            this.options = [{value: ''}]
          }
        }
      } else {
        this.name = ''
        this.disabledStatus = false
        this.parent_id = ''
        this.type = 0
        this.display_order = 0
        this.desc = ''
        this.options = [{value: ''}]
        this.section_id = ''
        this.source = 3
      }
    }
  },
  created() {
    this.getSectionList()
  },
  methods: {
    // 获取年段列表
    getSectionList() {
      sectionIndex({p: 0}).then(res => {
        if (!res.code) {
          this.sectionList = res.list.data || [];
        }
      });
    },
    checkEditFn() {
      if (!this.name) {
        this.$message.error('请填写动态反馈事项');
        return
      }
      let data = {
        name: this.name,
        parent_id: this.parent_id,
        type: this.type,
        display_order: this.display_order || 0,
        description: this.desc,
        section_id: parseInt(this.section_id),
        source: this.source,
        files: this.fileList.map(file => ({
          name: file.name,
          url: file.url || '',
          raw: file.raw
        }))
      }
      
      // 如果是打勾项，将options转换为分号分隔的字符串格式
      if (this.type === 0) {
        const validOptions = this.options.filter(option => option.value.trim())
        // 将选项数组用分号连接成字符串存储在description字段中
        data.description = validOptions.length > 0 ? validOptions.map(opt => opt.value.trim()).join(';') : ''
      } else {
        // 非打勾项，直接使用desc作为description
        const validDescription = this.desc.trim()
        data.description = validDescription
      }
      
      // 验证描述内容
      if (this.parent_id > 0 && this.type === 0) {
        const hasValidOption = this.options.some(option => option.value.trim())
        if (!hasValidOption) {
          this.$message.error('请添加选项内容');
          return
        }
      } else if (this.parent_id > 0 && !data.description) {
        this.$message.error('请添加描述内容');
        return
      }
      if (this.optionType === 'add') {
        DailyFeedbackCateAdd(data).then(res => {
          console.log('res:', res)
          this.$emit('InitFn')
          this.closePOpup()
        })
      } else {
        data.id = this.optionData.id
        DailyFeedbackCateEdit(data).then(res => {
          console.log('res:', res)
          this.$emit('InitFn')
          this.closePOpup()
        })
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    
    // 处理文件变化
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-3); // 限制最多上传3个文件
    },
    
    // 清空文件列表
    clearFiles() {
      this.fileList = [];
    },
    
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    changeParentsFn() {
      this.type = 0
    },
    
    // 添加选项
    addOption() {
      this.options.push({value: ''})
    },
    
    // 删除选项
    removeOption(index) {
      this.options.splice(index, 1)
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 500px;
  height: auto;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.recruitment-title {
  padding: 5px 0;
  border-bottom: 2px solid #abd3f3;
  margin-bottom: 20px;
}

.el-radio {
  margin-right: 20px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-item:last-child {
  margin-bottom: 0;
}

.jobTime {
  display: flex;
  align-items: center;
}

.jobTime span {
  padding: 0 10px;
}
</style>